﻿// ***********************************************************************
// 程 序 集  : HdhNetQuery
// 建立时间  : 2025-09
// 类库说明  ：Redis操作类
// 个人网站  ：http://www.hdhcms.com 
// ***********************************************************************
// <copyright>
//     Copyright by He DongHua(何冬华) All, QQ群:876705805 QQ:664627440 Email:664627440@qq.com
// </copyright>
// 如果要使用当前代码，请保存这些信息
// ***********************************************************************
using Microsoft.Extensions.Configuration;
using StackExchange.Redis;

namespace HdhNetQuery
{
    public static class HdhcmsRedisHelper
    {
        /// <summary>
        /// 获取连接字符串
        /// </summary>
        public static string? strConn = GetConnString();
        /// <summary>
        /// 返回连接字符串
        /// </summary>
        /// <returns></returns>
        public static string? GetConnString()
        {
            //核心依赖包
            //需要安装以下三个关键NuGet包才能使用SetBasePath方法：
            //Microsoft.Extensions.Configuration - 提供配置系统基础功能
            //Microsoft.Extensions.Configuration.FileExtensions - 包含文件相关的配置扩展方法
            //Microsoft.Extensions.Configuration.Json - 支持JSON文件配置读取
            var builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json");
            var configuration = builder.Build();
            string? hdhStr = configuration["ConnectionStrings:hdhConnRedis"];
            return hdhStr;
        }

        private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
        {
            string connectionString = strConn; // 根据实际情况修改连接字符串
            return ConnectionMultiplexer.Connect(connectionString);
        });

        public static ConnectionMultiplexer Connection => lazyConnection.Value;
        public static IDatabase GetDatabase()
        {
            return Connection.GetDatabase();
        }

        public static IServer GetServer(string host, int port)
        {
            return Connection.GetServer(host, port);
        }
        // 字符串操作
        public static void StringSet(string key, string value, TimeSpan? expiry = null)
        {
            GetDatabase().StringSet(key, value, expiry);
        }

        public static string StringGet(string key)
        {
            return GetDatabase().StringGet(key);
        }

        // 哈希操作
        public static void HashSet(string key, HashEntry[] hashFields)
        {
            GetDatabase().HashSet(key, hashFields);
        }

        public static string HashGet(string key, string hashField)
        {
            return GetDatabase().HashGet(key, hashField);
        }

        public static HashEntry[] HashGetAll(string key)
        {
            return GetDatabase().HashGetAll(key);
        }

        // 列表操作
        public static void ListRightPush(string key, string value)
        {
            GetDatabase().ListRightPush(key, value);
        }
        //根据键返回字符值
        public static string ListLeftPop(string key)
        {
            return GetDatabase().ListLeftPop(key);
        }

        // 集合操作
        public static void SetAdd(string key, string value)
        {
            GetDatabase().SetAdd(key, value);
        }
        /// <summary>
        /// 判断是否包含指定的键、值
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool SetContains(string key, string value)
        {
            return GetDatabase().SetContains(key,value);
        }

        // 有序集合的操作
        public static void SortedSetAdd(string key, string member, double score)
        {
            GetDatabase().SortedSetAdd(key, member, score);
        }

        public static double? SortedSetGetScore(string key, string member)
        {
            return GetDatabase().SortedSetScore(key, member);
        }
        // 事务示例
        public static bool TransactionExample(string key1, string key2)
        {
            var db = GetDatabase();
            var tran = db.CreateTransaction();
            tran.StringSetAsync(key1, "value1");
            tran.StringSetAsync(key2, "value2");
            return tran.Execute();
        }

        // 批量操作（使用Pipeline）
        public static void BatchOperation(List<KeyValuePair<string, string>> keyValues)
        {
            var db = GetDatabase();
            var batch = db.CreateBatch();
            foreach (var kv in keyValues)
            {
                batch.StringSetAsync(kv.Key, kv.Value);
            }
            batch.Execute();
        }

        // Lua脚本示例：实现一个简单的自增计数器，并返回自增后的值
        public static RedisResult ScriptExample(string key)
        {
            var db = GetDatabase();
            var script = LuaScript.Prepare("return redis.call('INCR', @key)");
            var result = db.ScriptEvaluate(script, new { key = (RedisKey)key });
            return result;
        }
        // 发布订阅相关
        public static void Subscribe(string channel, Action<RedisChannel, RedisValue> handler)
        {
            var sub = Connection.GetSubscriber();
            sub.Subscribe(channel, handler);
        }

        public static void Publish(string channel, string message)
        {
            var sub = Connection.GetSubscriber();
            sub.Publish(channel, message);
        }

    }
}
